<?php

namespace app\common\model\Subject;

use think\Model;

use traits\model\SoftDelete;

class Subject extends Model
{
    use SoftDelete;

    // 课程表
    protected $table = 'pre_subject';

    // 开启自动写入时间
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    // 定义软删除字段
    protected $deleteTime = 'deletetime';

    // 追加字段
    protected $append = [
        'like_count',
        'thumb_cdn',// 单图
        'thumbs_cdn'// 多图
    ];

    public function getLikeCountAttr($value,$data)
    {
        $likeArr = explode(',',$data['likes']);

        $likeArr = array_filter($likeArr);

        return count($likeArr);
    }

    public function getThumbsCdnAttr($value,$data)
    {
        $thumbs = explode(',',$data['thumbs']);

        $thumbs = array_filter($thumbs);

        // 获取网站地址
        $cdn = config('site.url');

        if(empty($thumbs))
        {
            // 设置默认图片
            return $cdn . '/assets/home/images/video3.png';
        }

        foreach($thumbs as &$val)
        {
            $val = $cdn . $val;
        }

        return $thumbs;
    }

    public function getThumbCdnAttr($value,$data)
    {
        $thumbs = explode(',',$data['thumbs']);

        $thumbs = array_filter($thumbs);

        $cdn = config('site.url');

        if(empty($thumbs))
        {
            return $cdn . '/assets/home/images/video3.png';
        }

        return $cdn . $thumbs[0];
    }

    // 分类关联查询
    public function category()
    {
        return $this->belongsTo('app\common\model\Subject\Category','cateid','id',[],'LEFT')->setEagerlyType(0);
    }
}
